<template>
  <DesktopLayout v-if="show">
    <template #head>
      <DesignHead :title="t('打印模板设计')">
        <template #steps
          ><a-steps :current="current">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" />
          </a-steps>
        </template>
        <template #buttons>
          <div class="design-button">
            <a-button :disabled="current == 0" @click="prev" class="common-button">
              {{ t('上一步') }}
            </a-button>
            <a-button :disabled="current == steps.length - 1" class="common-button" @click="next">{{
              t('下一步')
            }}</a-button>
            <a-button type="primary" class="common-button" :disabled="current == 0" @click="save">{{
              t('保存')
            }}</a-button>
            <a-button type="primary" class="clean-icon" @click="$emit('close')">{{
              t('关闭')
            }}</a-button>
          </div>
        </template>
      </DesignHead>
    </template>
    <Basic
      v-if="current == 0"
      :basicData="data.basicData"
      :apiConfig="data.apiConfig"
      ref="basicRef"
    />
    <iframe v-if="current == 1" ref="iframe" :src="printIframeUrl" class="iframe-box"></iframe>
    <LoadingBox v-if="showLoading" />
  </DesktopLayout>
</template>

<script setup lang="ts">
  import DesignHead from '/@/views/generator/desktop/components//designer/layout/Head.vue';
  import DesktopLayout from '/@/views/generator/desktop/components/designer/layout/Desktop.vue';
  import Basic from './Basic.vue';
  import { computed, nextTick, onMounted, reactive, ref } from 'vue';
  import { PrintBasicData } from '/@/model/generator/print';
  import { getPrintData } from './hooks/usePrintData';
  import { PrintBaseUrl, iframeUrl } from './config';
  import { ApiConfig } from '/@/components/ApiConfig/src/interface';
  import { LoadingBox } from '/@/components/ModalPanel/index';
  import { addDesign, editDesign } from '/@/api/system/generator/print';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  let iframe = ref();
  const current = ref<number>(0);
  let basicRef = ref();
  let show = ref(false);
  const { notification } = useMessage();
  const { t } = useI18n();
  const showLoading = ref(false);
  const steps = [
    {
      title: t('基本配置'),
      content: t('基本配置'),
    },
    {
      title: t('打印设计'),
      content: t('打印设计'),
    },
  ];
  const props = withDefaults(
    defineProps<{
      editData: PrintBasicData;
    }>(),
    {
      editData: () => {
        return {
          id: '',
          code: '',
          name: '',
          icon: '',
          category: '',
          parentId: '',
          sortCode: 0,
          isMenu: 0,
          remark: '',
          apiConfig: '',
          content: '',
        };
      },
    },
  );
  let emits = defineEmits(['close']);
  const printIframeUrl = computed(() => {
    return iframeUrl + '?type=' + data.urlType;
  });
  const data: {
    basicData: PrintBasicData;
    printData: Object;
    apiConfig: ApiConfig;
    apiFields: Array<{ text: string; field: string }>;
    subTabulation: Array<{
      text: string;
      field: string;
      columns: Array<{ text: string; field: string }>;
    }>;
    isSave: boolean;
    isHoldPrevSave: boolean;
    urlType: number;
  } = reactive({
    basicData: {
      code: '',
      name: '',
      icon: '',
      category: '',
      parentId: '',
      apiConfig: '',
      sortCode: 0,
      isMenu: 0,
      remark: '',
      content: '',
    },
    apiConfig: {
      id: '',
      name: '',
      method: '',
      requestParamsConfigs: [], //Query Params
      requestHeaderConfigs: [], //Header
      requestBodyConfigs: [], //Body
    },
    apiFields: [],
    subTabulation: [],
    printData: {},
    isSave: false,
    isHoldPrevSave: false,
    urlType: Math.random() * 10,
  });
  onMounted(async () => {
    if (props.editData.id) {
      data.basicData = props.editData;
      data.apiConfig = JSON.parse(props.editData.apiConfig);
    }
    show.value = true;
  });
  const next = async () => {
    if (current.value == 0) {
      let validate = await basicRef.value.validateForm();
      if (validate) {
        data.apiConfig = basicRef.value.getApiData();
        data.basicData = basicRef.value.getBasicData();
        data.basicData.apiConfig = JSON.stringify(data.apiConfig);
        current.value++;
        await nextTick();
        iframe.value.onload = function () {
          sendMessage();
          window.addEventListener('message', function (event) {
            if (event.data.urlType == data.urlType && event.origin === PrintBaseUrl) {
              if (!data.isSave) {
                data.isSave = true;
                data.basicData.content = event.data.json;
                showLoading.value = true;
                submit();
              }
            }
          });
        };
      }
    }
  };
  const prev = () => {
    holdSave();
  };
  async function sendMessage() {
    try {
      let printData = await getPrintData(data.apiConfig);
      let json = '';
      // 编辑
      if (data.basicData.content) {
        json = data.basicData.content;
      }
      let info = {
        type: 'api',
        fields: printData.apiFields,
        subTabulation: printData.subTabulation,
        printData: printData.data,
        json,
      };
      var wn = iframe.value.contentWindow;
      wn.postMessage(info, PrintBaseUrl);
    } catch (error) {}
  }
  function save() {
    data.isSave = false; //防止重复发送消息 重复提交
    data.isHoldPrevSave = false;
    var wn = iframe.value.contentWindow;
    wn.postMessage({ type: 'save' }, PrintBaseUrl);
  }
  function holdSave() {
    data.isSave = false; //防止重复发送消息 重复提交
    data.isHoldPrevSave = true;
    var wn = iframe.value.contentWindow;
    wn.postMessage({ type: 'save' }, PrintBaseUrl);
  }
  async function submit() {
    if (data.isHoldPrevSave) {
      current.value--;
      showLoading.value = false;
      return true;
    }
    try {
      if (data.basicData.id) {
        let res = await editDesign(data.basicData);
        if (res) {
          notification.success({
            message: t('提示'),
            description: t('编辑成功'),
          }); //提示消息
          close();
        }
      } else {
        let res = await addDesign(data.basicData);
        if (res) {
          notification.success({
            message: t('提示'),
            description: t('新增成功'),
          }); //提示消息
          close();
        }
      }
    } catch (error) {}
  }
  function close() {
    setTimeout(() => {
      data.isSave = true;
      showLoading.value = false;
      emits('close');
    }, 1);
  }
</script>

<style scoped>
  .iframe-box {
    width: 100%;
    height: 100%;
    position: fixed;
    inset: 50px 0 0;
    z-index: 0;
  }

  .common-button {
    margin-right: 4px;
  }
</style>
